package com.bocai.dahuatech.ui.activity;

import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.bocai.dahuatech.Bean.AddressListBean;
import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.ConfirmOrderBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseActivity;
import com.bocai.dahuatech.ui.adapter.ConfirmOrderAdapter;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.google.gson.Gson;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ConfirmOrderActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.lv_confirm_order)
    ListView lvConfirmOrder;
    @Bind(R.id.tv_confirm)
    TextView tvConfirm;

    @Bind(R.id.tv_totalprice)
    TextView tvtotalPrice;
    View hearder;
    View footer;
    TextView tvChangeAddr,tvName,tvAddr,tvZipCode,tvPhone,tvPrice,tvCount;
    EditText etNote;
    ConfirmOrderBean confirmOrderBean;
    AddressListBean addrBean;
    int addrId=-1;
    AddressListBean.ContentEntity bean;
    String totalprice="0";
    int totalCount;
    @Override
    protected int contentView() {
        return R.layout.activity_confirm_order;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        initToolbar(R.string.cofirmorder);
        getData();
        hearder= LayoutInflater.from(this).inflate(R.layout.confirmorder_header,null);
        footer=LayoutInflater.from(this).inflate(R.layout.confirmorder_footer,null);
        tvChangeAddr=(TextView)hearder.findViewById(R.id.tv_confirmorder_changeaddress);
        tvName= (TextView) hearder.findViewById(R.id.tv_confirmorder_name);
        tvAddr= (TextView) hearder.findViewById(R.id.tv_confirmorder_addr);
        tvZipCode= (TextView) hearder.findViewById(R.id.tv_confirmorder_zipcode);
        tvPhone= (TextView) hearder.findViewById(R.id.tv_confirmorder_phone);
        etNote=(EditText)hearder.findViewById(R.id.et_confirmorder_note);
        tvCount=(TextView)footer.findViewById(R.id.tv_totalcount);
        tvPrice=(TextView)footer.findViewById(R.id.tv_order_totalprice);
        lvConfirmOrder.addHeaderView(hearder);
        lvConfirmOrder.addFooterView(footer);
        initEvent();
    }

    /**
     * 确认购物车列表
     */
    private void getData() {
        showLoading();
        getTestApi().getSummitCartList(SharePrefencesUtil.getFID(this) + "")
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);

    }
    Observer<BaseBean> observer=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {
            if(confirmOrderBean.getContent().size()!=0){
                for (int i=0;i<confirmOrderBean.getContent().size();i++){
                    totalCount=totalCount+confirmOrderBean.getContent().get(i).getFAQty();
//                    totalprice=totalprice+confirmOrderBean.getContent().get(i).getFAQty()*confirmOrderBean.getContent().get(i).getFStandPrice();
                }
            }
            tvCount.setText(getResources().getString(R.string.gong)+totalCount+getResources().getString(R.string.productcount));
            tvPrice.setText(getResources().getString(R.string.moneytotal)+totalprice);
            tvtotalPrice.setText(getResources().getString(R.string.moneytotal)+totalprice);
        }

        @Override
        public void onError(Throwable e) {
            hideLoading();
            showToast(R.string.neterror);
            Log.e("error",e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean) {
            hideLoading();
            getAddress();
            if(baseBean.getReturnNo().equals("1"))
            {
                String result= AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                confirmOrderBean=new Gson().fromJson(result,ConfirmOrderBean.class);
                lvConfirmOrder.setAdapter(new ConfirmOrderAdapter(ConfirmOrderActivity.this, confirmOrderBean.getContent()));
                totalprice=baseBean.getReturnInfo();
            }else{
                showToast(baseBean.getReturnInfo());
            }
        }
    };

    /**
     * 获取用户收货地址
     */
    private void getAddress() {
        getTestApi().getAddrList(SharePrefencesUtil.getCustomerCode(this))
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(addressObserver);
    }
    Observer<BaseBean> addressObserver=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            hideLoading();
            showToast(R.string.neterror);
        }

        @Override
        public void onNext(BaseBean baseBean) {
            if(baseBean.getReturnNo().equals("1"))
            {
                String result= AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                addrBean=new Gson().fromJson(result,AddressListBean.class);
                if(addrBean.getContent().size()!=0){
                    bean=addrBean.getContent().get(0);
                    addrId=addrBean.getContent().get(0).getFID();
                    setAddr();
                }
            }else
            {
                showToast(baseBean.getReturnInfo());
            }
        }
    };

    /**
     * 设置收货地址数据
     */
    private void setAddr() {
            tvName.setText(bean.getFConsignee());
            tvAddr.setText(bean.getPCAName() + bean.getFAddress());
            tvZipCode.setText(bean.getFZipCode());
            tvPhone.setText(bean.getFMobilePhone());

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        tvConfirm.setOnClickListener(this);
        tvChangeAddr.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.tv_confirm:
                //结算
                if(addrId!=-1){
                    toAcount();
                }else{
                showToast(R.string.choosegoodsaddress);
                }
                break;
            case R.id.tv_confirmorder_changeaddress:
                //修改收货地址
                Intent intent=new Intent(this, MyAddressActivity.class);
                intent.putExtra("what","choose");
                startActivityForResult(intent, 1000);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if(requestCode==1000)
            {
                if (resultCode==2000)
                {
                    if(data!=null)
                    {
                        bean= (AddressListBean.ContentEntity) data.getSerializableExtra("data");
                        addrId=bean.getFID();
                        tvName.setText(bean.getFConsignee());
                        tvAddr.setText(bean.getPCAName() + bean.getFAddress());
                        tvZipCode.setText(bean.getFZipCode());
                        tvPhone.setText(bean.getFMobilePhone());
                    }
                }
            }
    }

    /**
     * 购物车结算
     */
    private void toAcount() {
        getTestApi().toAcount(confirmOrderBean.getContent().get(0).getFID(),SharePrefencesUtil.getCustomerCode(this))
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(confirmObserver);
    }
    Observer<BaseBean> confirmObserver=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            hideLoading();
            showToast(R.string.neterror);
            Log.e("error",e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean) {
            Log.e("result",baseBean.getReturnInfo());
            if(baseBean.getReturnInfo().equals(getResources().getString(R.string.confirmsucces))&&baseBean.getReturnNo().equals("1")){
                //确认订单
                saveOrder();
            }
        }
    };

    /**
     * 确认订单
     */
    private void saveOrder() {
        Log.e("info",SharePrefencesUtil.getFID(this)+"");
        Log.e("info",addrId+"");
        Log.e("info",confirmOrderBean.getContent().get(0).getFID()+"");
        Log.e("info",SharePrefencesUtil.getCustomerCode(this)+"");
        getTestApi().saveOrder(SharePrefencesUtil.getFID(this),addrId,confirmOrderBean.getContent().get(0).getFID(),
                etNote.getText().toString(),"1",SharePrefencesUtil.getCustomerCode(this))
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(saveOrderObserver);

    }
    Observer<BaseBean> saveOrderObserver=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            hideLoading();
            showToast(R.string.neterror);
            Log.e("error",e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean) {
            if(baseBean.getReturnNo().equals("1")){
                Log.e("result",baseBean.getReturnInfo());
                showToast(baseBean.getReturnInfo());
                finish();
            }else{
                showToast(baseBean.getReturnInfo());

            }
        }
    };

}
